package concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DemoComdition {

	public static void main(String[] args) {

		final String[] keys = { "hongxingfan", "wenxiubi", "guangweicao", "xiaoyanwang", "aaa", "bbb", "ccc",
		        "ddd", "eee", "fff" };

		final DemoCondition condition = new DemoCondition();

		ExecutorService exec = Executors.newCachedThreadPool();
		exec.submit(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						System.out.println(Thread.currentThread().getName() + "-->get:" + condition.take());
						Thread.sleep(1 * 400);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		exec.submit(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						System.out.println(Thread.currentThread().getName() + "-->get:" + condition.take());
						Thread.sleep(1 * 200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		exec.submit(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						System.out.println(Thread.currentThread().getName() + "-->get:" + condition.take());
						Thread.sleep(1 * 300);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		exec.submit(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						int index = (int) (Math.random() * 10);
						System.out.println(Thread.currentThread().getName() + "-->put:" + keys[index]);
						condition.put(keys[index]);
						Thread.sleep(1 * 100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

}

class DemoCondition {
	private Lock lock = new ReentrantLock();
	private Condition notFull = lock.newCondition(); // 唤醒特定线程；区别于wait和notify
	private Condition notEmpty = lock.newCondition();

	private Object[] items = new Object[5];
	private int putptr, takeptr, count;

	public void put(Object x) throws InterruptedException {
		lock.lock();
		try {
			while (count == items.length)
				notFull.await();
			items[putptr] = x;
			if (++putptr == items.length)
				putptr = 0;
			++count;
			notEmpty.signal();
		} finally {
			lock.unlock();
		}
	}

	public Object take() throws InterruptedException {
		lock.lock();
		try {
			while (count == 0)
				notEmpty.await();
			Object x = items[takeptr];
			if (++takeptr == items.length)
				takeptr = 0;
			--count;
			notFull.signal();
			return x;
		} finally {
			lock.unlock();
		}
	}
}
